package com.davfx.restream;

import java.io.IOException;
import java.nio.ByteBuffer;

import com.davfx.httpnio.HttpResponse;
import com.davfx.util.Log;

final class Recorder {
	
	private final DatabaseWriter databaseWriter;
	private final long from;
	private long initTime;
	private boolean errored = false;
	
	public Recorder(Database database, long from, HttpResponse response) {
		databaseWriter = database.getWriter(from);
		this.from = from;
		try {
			databaseWriter.setHttpResponse(response);
		} catch (IOException e) {
			Log.error("Could not record", e);
			errored = true;
		}
		initTime = System.currentTimeMillis();
		
	}
	
	public void closed() {
		databaseWriter.close();
	}
	
	public void handle(ByteBuffer content) {
		if (errored) {
			return;
		}
		
		long delta = System.currentTimeMillis() - initTime;
		
		try {
			databaseWriter.write(from + delta, content);
		} catch (IOException e) {
			Log.error("Could not record", e);
		}
	}
}
